package com.atao.baokede.interceptors;

import com.atao.baokede.utils.JwtUtil;
import com.atao.baokede.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import com.atao.baokede.enums.TokenType;
import java.util.Map;

//登录拦截器
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //令牌验证
        String token = request.getHeader("Authorization");
        //验证token
        try {
            // 通过JWT内容判断是用户还是商户
            TokenType tokenType = JwtUtil.getTokenType(token);
            if(tokenType==null){
                throw new RuntimeException();
            }
            if(tokenType==TokenType.USER){
                Map<String,Object> claims= JwtUtil.parseToken(token);
                //把业务数据存储到ThreadLocal中
                ThreadLocalUtil.set(claims);
                System.out.println("识别为用户请求: " + request.getRequestURI());
                return true;
            } else if (tokenType == TokenType.MERCHANT) {
                // 处理商户token
                Map<String, Object> claims = JwtUtil.parseToken(token);
                ThreadLocalUtil.setMerchant(claims);  // 存储到商户ThreadLocal
                System.out.println("识别为商户请求: " + request.getRequestURI());
                return true;
            }
            return false;
        } catch (Exception e) {
            System.out.println("拦截请求路径: " + request.getRequestURI());
            //http相应状态码为401
            response.setStatus(401);
            return false;
        }
    }

    //并在该方法后重写一个新方法，保证使用完该数据后清除线程内的数据，防止内存泄漏
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清空ThreadLocal中的数据
        ThreadLocalUtil.remove();
    }
}
